package com.yuhf.dbutils;

import com.yuhf.dbutils.exception.AccessDbException;
import com.yuhf.dbutils.exception.TranscationException;
import lombok.extern.log4j.Log4j;

import java.sql.Connection;
import java.sql.SQLException;

@Log4j
public class TranscationManager {
    public static void beginTranscation() throws TranscationException {
        Connection connection = DBConnection.getConnection();
        try {
            connection.setAutoCommit(false);    //设置自动提交为false，开启事务
        } catch (SQLException e) {
            log.error("begin transcation error,message is "+e.getMessage());
            throw new TranscationException("事务开启失败");
        }
    }
    public static void commit() throws TranscationException {
        try(Connection connection = DBConnection.getConnection()){
            connection.commit();    //提交事务
            connection.setAutoCommit(true); //设置自动提交为true，关闭事务
        } catch (SQLException e) {
            log.error("commit transcation error,message is "+e.getMessage());
            throw new TranscationException("事务提交失败");
        }
    }
    public static void rollback()  {
        try(Connection connection = DBConnection.getConnection()){
            connection.rollback();  //回滚事务
            connection.setAutoCommit(true); //设置自动提交为true，关闭事务
        } catch (SQLException e) {
            log.error("rollback transcation error,message is "+e.getMessage());
            throw new AccessDbException("事务回滚失败");
        }
    }
}
